package com.example.test_app.view;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragmentsList;
    private FragmentManager mFm;


    public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragmentsList = fragments;
        this.mFm = fm;
    }

    @Override
    public int getCount() {
        return fragmentsList.size();
    }

    @Override
    public Fragment getItem(int arg0) {

        Log.d("TAG", "getItem: "+arg0);
        return fragmentsList.get(arg0);
    }

    @Override
    public int getItemPosition(Object object) {
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        //得到缓存的fragment
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        this.mFm.beginTransaction().show(fragment).commitNowAllowingStateLoss();
        return fragment;
    }

    public void destroyAllItem(){
        FragmentTransaction fragmentTransaction=mFm.beginTransaction();
        for (int i = 0; i <fragmentsList.size() ; i++) {
            fragmentTransaction.remove(fragmentsList.get(i));
        }
        fragmentTransaction.commitNowAllowingStateLoss();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = fragmentsList.get(position);
        mFm.beginTransaction().remove(fragment).commitNowAllowingStateLoss();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return super.isViewFromObject(view, object);
    }
}